package com.x.control;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.x.service.transactional.UserService;

@Controller
public class MainController {
	@Autowired(required = true)
	UserService userService;

	@RequestMapping(value = "/")
	public ModelAndView base() {
		return home("dashBoard");
	}

	@RequestMapping(value = "/home")
	public ModelAndView homebase() {
		return home("dashBoard");
	}

	@RequestMapping(value = "/home/{nav}")
	public ModelAndView home(@PathVariable(value = "nav") String nav) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("nav", nav);
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		String username;
		if (principal instanceof UserDetails) {
			username = ((UserDetails) principal).getUsername();
		} else {
			username = principal.toString();
		}
		String role = userService.getRoleByName(username);
		mv.addObject("username", username);
		mv.addObject("role", role);
		mv.setViewName("home");
		return mv;
	}

	@RequestMapping(value = "/signin")
	public String signin() {
		return "signin";
	}

}
